from django.http import JsonResponse
from rest_framework.authentication import TokenAuthentication
from rest_framework.response import Response
from django.contrib import auth
from app.serializer import CardAPISerializer
from .models import *
from django.shortcuts import HttpResponse
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.authtoken.models import Token


# authentication是身份认证，判断当前用户的登录方式是哪种认证方式
# permissions 是权限认证，判断哪些用户有操作权限
@api_view(['POST'])
def Login(request):
    username = request.data.get('username')
    # print(username)
    password = request.data.get('password')
    user = auth.authenticate(username=username, password=password)
    if not user:
        return HttpResponse({"code": 0,
                             "msg": "用户名或密码不对!"})
    # 删除原有的Token
    old_token = Token.objects.filter(user=user)
    old_token.delete()
    # 创建新的Token
    token = Token.objects.create(user=user)
    return JsonResponse({"code": 0,
                         "msg": "login success!",
                         "username": user.username,
                         "token": token.key})


@api_view(['GET', 'POST'])
# 单个接口权限控制
# @authentication_classes([TokenAuthentication])  # token认证
# @permission_classes([IsAuthenticated])  # 认证通过的用户访问
def card_list_view(request):
    '''基于函数式实现get和post请求'''
    cards = Card.objects.all()
    serializer = CardAPISerializer(cards, many=True)
    if request.method == 'GET':
        return Response(serializer.data)

    elif request.method == 'POST':
        verify_data = CardAPISerializer(data=request.data)
        if verify_data.is_valid():
            verify_data.save()
            return Response({"message": "create some data!", "data": request.data})
        else:
            return Response(verify_data.errors)
    else:
        return Response({"message": "request method mot valid!"})
